class Solution:
    def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int:
        m, n = len(obstacleGrid), len(obstacleGrid[0])
        f = [[0] * n for _ in range(m)]
        # 2.初始化边界条件：
        # 2.1 dp[i][0]=1；只有一列，因此只有一种走法（向下走，前提条件是没有碰到障碍物）
        for i in range(m):
            if obstacleGrid[i][0] == 1:
                break
            f[i][0] = 1
        # 2.2 只有一行，因此只有一种走法（向右走，前提条件是没有碰到障碍物）
        for j in range(n):
            if obstacleGrid[0][j] == 1:
                break
            f[0][j] = 1
        for i in range(1, m):
            for j in range(1, n):
                if obstacleGrid[i][j] == 1:
                    f[i][j] = 0
                else:
                    f[i][j] = f[i - 1][j] + f[i][j - 1]
        return f[m - 1][n - 1]